package io.github.openfeign.spring.multi;

import lombok.Getter;
import lombok.RequiredArgsConstructor;
import lombok.SneakyThrows;
import org.apache.commons.io.IOUtils;
import org.springframework.lang.NonNull;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;

@RequiredArgsConstructor
@Getter
public class StreamMultipartFile implements MultipartFile, AutoCloseable {

    private final InputStream inputStream;
    private final String name;
    private final String contentType;


    @Override
    public String getOriginalFilename() {
        return name;
    }


    @Override
    public boolean isEmpty() {
        return getSize() == 0;
    }

    @Override
    public long getSize() {
        try {
            return inputStream.available();
        } catch (final IOException e) {
            return 0;
        }
    }

    @SneakyThrows
    @Override
    public byte[] getBytes() {
        return IOUtils.toByteArray(inputStream);
    }

    @Override
    public InputStream getInputStream() {
        return inputStream;
    }

    @Override
    public void transferTo(@NonNull final File dest) throws IllegalStateException {
        throw new UnsupportedOperationException();
    }


    @Override
    public void close() {
        if (inputStream != null) {
            IOUtils.closeQuietly(inputStream);
        }
    }
}
